package com.mmall.service;

import com.google.common.base.Joiner;
import com.mmall.beans.CacheKeyConstants;
import com.mmall.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import redis.clients.jedis.ShardedJedis;

import javax.annotation.Resource;

/**
 * @Auther 19135
 * @Date 2019/3/26 21:18
 * @Description ${end}$
 */
@Service
@Slf4j
public class SysCacheService {

	@Resource(name = "redisPool")
	private RedisPool redisPool;

	public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix) {
		saveCache(toSavedValue, timeoutSeconds, prefix, null);
	}

	public void saveCache(String toSavedValue, int timeoutSeconds, CacheKeyConstants prefix, String... keys) {
		if (toSavedValue == null){
			return;
		}
		ShardedJedis shardedJedis = null;
		try {
			String cacheKey = generateCacheKey(prefix, keys);
			ShardedJedis instance = redisPool.instance();
			shardedJedis.setex(cacheKey, timeoutSeconds, toSavedValue);
		} catch (Exception e) {
			log.error("save cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
		} finally {
			redisPool.safeClose(shardedJedis);
		}
	}

	public String getFormCache(CacheKeyConstants prefix, String... keys){
		ShardedJedis shardedJedis = null;
		String cacheKey = generateCacheKey(prefix, keys);
		try {
			shardedJedis = redisPool.instance();
			String value = shardedJedis.get(cacheKey);
			return value;
		} catch (Exception e) {
			log.error("get from cache exception, prefix:{}, keys:{}", prefix.name(), JsonMapper.obj2String(keys), e);
			return null;
		} finally {
			redisPool.safeClose(shardedJedis);
		}
	}



	//将key用_连接并且加上前缀
	private String generateCacheKey(CacheKeyConstants prefix,String ...keys){
		String key = prefix.name();
		if (keys != null && keys.length>0){
			key +=  "_" + Joiner.on("_").join(keys);
		}
		return key;
	}
}
